﻿using ClosedXML.Excel;
using Dapper;
using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Text.RegularExpressions;
using System.Windows.Forms;

namespace WaterResources
{
    public partial class FormWaterSecurity : Form
    {
        public FormWaterSecurity()
        {
            InitializeComponent();

            var db = new WaterResourcesDb<WaterSecurity>();
            var wsSource = db.Find();
            foreach (WaterSecurity we in wsSource)
            {
                if (we.Level == 1) { we.Levelname = "第一级"; }
                else if (we.Level == 2) { we.Levelname = "第二级"; }
                else if (we.Level == 3) { we.Levelname = "第三级"; }
                else if (we.Level == 4) { we.Levelname = "第四级"; }
                else if (we.Level == 5) { we.Levelname = "第五级"; }
            }
            dataGridView1.DataSource = wsSource;
            mapDataGridViewHeader();
        }

        private void FormWaterSecurity_FormClosed(object sender, FormClosedEventArgs e)
        {
            Application.OpenForms[0].Show();
        }

        private string validateInputIsInt(string input)
        {
            var output = input;
            var regex = new Regex(@"^\d*$");
            if (!regex.IsMatch(input))
            {
                regex = new Regex(@"[^\d]");
                output = regex.Replace(input, "");
            }
            return output;
        }

        private string validateInputIsDecimal(string input)
        {
            var output = input;
            var regex = new Regex(@"^\d+\.?\d*$");
            if (!regex.IsMatch(input))
            {
                regex = new Regex(@"[^\d\.]");
                output = regex.Replace(input, "");
            }
            while (output.IndexOf('.') != output.LastIndexOf('.'))
            {
                output = output.Substring(0, output.LastIndexOf('.'));
            }
            return output;
        }

        private void mapDataGridViewHeader()
        {
            dataGridView1.Columns["Id"].HeaderText = "编号";
            dataGridView1.Columns["Id"].Width = 55;
            dataGridView1.Columns["Level"].HeaderText = "河道防洪排涝等级";
            dataGridView1.Columns["Level"].Width = 130;
            dataGridView1.Columns["Level"].Visible = false;
            dataGridView1.Columns["Levelname"].HeaderText = "等级";
            dataGridView1.Columns["Levelname"].Width = 55;
            dataGridView1.Columns["Name"].HeaderText = "河道名称";
            dataGridView1.Columns["Name"].Width = 80;
            dataGridView1.Columns["Area"].HeaderText = "河道所属辖区";
            dataGridView1.Columns["Area"].Width = 110;
            dataGridView1.Columns["Start"].HeaderText = "河道起点";
            dataGridView1.Columns["Start"].Width=80;
            dataGridView1.Columns["End"].HeaderText = "河道终点";
            dataGridView1.Columns["End"].Width = 80;
            dataGridView1.Columns["RiverWidth"].HeaderText = "河道宽度(m)";
            dataGridView1.Columns["RiverWidth"].Width = 105;
            dataGridView1.Columns["Ratio"].HeaderText = "边坡比";
            dataGridView1.Columns["Ratio"].Width = 70;
            dataGridView1.Columns["Elevation"].HeaderText = "设计河底高程(m)";
            dataGridView1.Columns["Elevation"].Width = 120;
            dataGridView1.Columns["Line"].HeaderText = "设计洪水水位(m)";
            dataGridView1.Columns["Line"].Width = 120;
            dataGridView1.Columns["Allow"].HeaderText = "是否允许浪爬高";
            dataGridView1.Columns["Allow"].Width = 120;
            dataGridView1.Columns["Safe"].HeaderText = "安全超高(m)";
            dataGridView1.Columns["Safe"].Width = 105;
            dataGridView1.Columns["Depth"].HeaderText = "淤积深度(m)";
            dataGridView1.Columns["Depth"].Width = 105;
            dataGridView1.Columns["ChannelWidth"].HeaderText = "河槽宽度(m)";
            dataGridView1.Columns["ChannelWidth"].Width = 105;
            dataGridView1.Columns["Threshold"].HeaderText = "淤积阈值(m)";
            dataGridView1.Columns["Threshold"].Width = 105;
            dataGridView1.Columns["Dredging"].HeaderText = "清淤判断";
            dataGridView1.Columns["Dredging"].Width = 140;
            dataGridView1.Columns["Time"].HeaderText = "录入时间";
            
        }

        private void level_Scroll(object sender, EventArgs e)
        {
            var level = sender as TrackBar;
            switch (level.Value)
            {
                case 1: levelText.Text = "第一级"; break;
                case 2: levelText.Text = "第二级"; break;
                case 3: levelText.Text = "第三级"; break;
                case 4: levelText.Text = "第四级"; break;
                case 5: levelText.Text = "第五级"; break;
                default: levelText.Text = "第一级"; break;
            }
        }

        private void riverWidth_TextChanged(object sender, EventArgs e)
        {
            var textBoxRiverWidth = sender as TextBox;
            if (textBoxRiverWidth.Text != "" && Convert.ToDecimal(textBoxRiverWidth.Text) == 0)
            {
                MessageBox.Show("边坡比不能填写0！");
                riverWidth.Text = "";
            }
            else {
                riverWidth.Text = validateInputIsDecimal(textBoxRiverWidth.Text);
            }
            
        }

        private void ratio_TextChanged(object sender, EventArgs e)
        {
            var textBoxRatio = sender as TextBox;
            ratio.Text = validateInputIsDecimal(textBoxRatio.Text);
        }

        private void elevation_TextChanged(object sender, EventArgs e)
        {
            var textBoxElevation = sender as TextBox;
            elevation.Text = validateInputIsDecimal(textBoxElevation.Text);
        }

        private void line_TextChanged(object sender, EventArgs e)
        {
            var textBoxLine = sender as TextBox;
            line.Text = validateInputIsDecimal(textBoxLine.Text);
        }

        private void safe_TextChanged(object sender, EventArgs e)
        {
            var textBoxSafe = sender as TextBox;
            safe.Text = validateInputIsDecimal(textBoxSafe.Text);
        }

        private void depth_TextChanged(object sender, EventArgs e)
        {
            var textBoxDepth = sender as TextBox;
            depth.Text = validateInputIsDecimal(textBoxDepth.Text);
        }
        

        private void buttonSubmit_Click(object sender, EventArgs e)
        {
            if (name.Text == "" || area.Text == "" || start.Text == "" || end.Text == "" || riverWidth.Text == "" || elevation.Text == "" || line.Text == "" || safe.Text == "" || depth.Text == "")
            {
                MessageBox.Show("警告:可输入的框中值不能为空！");
                return;
            }
            if (!area.Text.Contains("市") && !area.Text.Contains("县") && !area.Text.Contains("区") && !area.Text.Contains("乡") && !area.Text.Contains("一般"))
            {
                MessageBox.Show("河道所属辖区，请填写关键字【市】或者【县】或者【区】或者【乡】或者【一般】！");
                return;
            }
            else if (ratioTrue.Checked == true && (ratio.Text == "" || Convert.ToDecimal(ratio.Text) == 0))
            {
                MessageBox.Show("警告:是否有边坡比选中了【是】，比例值不能为空或者0！");
                return;
            }
            else if (ratioFalse.Checked == true)
            {
                ratio.Text = "0";
            }
            else if (ratioTrue.Checked == false && ratioFalse.Checked == false)
            {
                MessageBox.Show("警告:请选择【是否有边坡比】！");
                return;
            }
            WRFormula wrf = new WRFormula();
            string y = "";
            if (area.Text.Contains("乡") || area.Text.Contains("一般"))
            {
                y = "3";
            }
            else if (area.Text.Contains("县") || area.Text.Contains("区"))
            {
                y = "2";
            }
            else if (area.Text.Contains("市")) {
                y = "1";
            }
            else {
                y = "3";
            }
            string x = wrf.SecurityFormula(Convert.ToDouble(ratio.Text),y, Convert.ToDouble(depth.Text), Convert.ToDouble(riverWidth.Text), Convert.ToDouble(line.Text), Convert.ToDouble(safe.Text));
            
            var ws = new WaterSecurity
            {
                Level = level.Value,
                Name = name.Text,
                Area = area.Text,
                Start = start.Text,
                End = end.Text,
                RiverWidth = Convert.ToDecimal(riverWidth.Text),
                Ratio = Convert.ToDecimal(ratio.Text),
                Elevation = Convert.ToDecimal(elevation.Text),
                Line = Convert.ToDecimal(line.Text),
                Allow = 1,
                Safe = Convert.ToDecimal(safe.Text),
                Depth = Convert.ToDecimal(depth.Text),
                ChannelWidth = Convert.ToDecimal(wrf.BottomWidth(Convert.ToDouble(riverWidth.Text), Convert.ToDouble(line.Text), Convert.ToDouble(safe.Text), Convert.ToDouble(ratio.Text))),
                Threshold = Convert.ToDecimal(x.Split('&')[0]),
                Dredging = x.Split('&')[1],
                Time = DateTime.Now,
            };
            if (!string.IsNullOrEmpty(id.Text) && new Regex(@"\d").IsMatch(id.Text))
            {
                ws.Id = Convert.ToInt32(id.Text);
            }
            var db = new WaterResourcesDb<WaterSecurity>();
            int num;
            if (ws.Id == 0)
            {
                num = db.Save(ws);
            }
            else
            {
                num = db.Edit(ws);
            }
            if (num == 1)
            {
                channelWidth.Text = ws.ChannelWidth.ToString();
                threshold.Text = ws.Threshold.ToString();
                if (ws.Dredging == "不需要清淤.") {
                    dredging.ForeColor = System.Drawing.Color.Green;
                } else if (ws.Dredging == "需要对该河道进行清淤.") {
                    dredging.ForeColor = System.Drawing.Color.Red;
                }
                else
                {
                    dredging.ForeColor = System.Drawing.Color.Blue;
                }
                dredging.Text = ws.Dredging;
                MessageBox.Show(ws.Id == 0 ? "添加成功" : "修改成功");
                var wsSource = db.Find();
                foreach (WaterSecurity we in wsSource)
                {
                    if (we.Level == 1) { we.Levelname = "第一级"; }
                    else if (we.Level == 2) { we.Levelname = "第二级"; }
                    else if (we.Level == 3) { we.Levelname = "第三级"; }
                    else if (we.Level == 4) { we.Levelname = "第四级"; }
                    else if (we.Level == 5) { we.Levelname = "第五级"; }
                }
                dataGridView1.DataSource = wsSource;
                dataGridView1.DataSource = wsSource;
                mapDataGridViewHeader();
            }
            else
            {
                MessageBox.Show("添加失败");
            }
        }

        private void buttonReset_Click(object sender, EventArgs e)
        {
            id.ResetText();
            level.Value = 1;
            levelText.Text = "第一级";
            name.ResetText();
            area.ResetText();
            start.ResetText();
            end.ResetText();
            riverWidth.ResetText();
            ratioTrue.Checked = false;
            ratioFalse.Checked = false;
            ratio.ResetText();
            elevation.ResetText();
            line.ResetText();
            allowTrue.Checked = false;
            allowFalse.Checked = false;
            allowCustom.Checked = false;
            safe.ResetText();
            depth.ResetText();
            channelWidth.ResetText();
            threshold.ResetText();
            dredging.ResetText();
        }

        private void buttonQuit_Click(object sender, EventArgs e)
        {
            Close();
        }

        private void dataGridView_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
        {
            var dgv = sender as DataGridView;
            var cells = dgv.SelectedRows[0].Cells;
            id.Text = cells["Id"].Value.ToString();
            level.Value = Convert.ToInt32(cells["Level"].Value);
            switch (level.Value)
            {
                case 1: levelText.Text = "第一级"; break;
                case 2: levelText.Text = "第二级"; break;
                case 3: levelText.Text = "第三级"; break;
                case 4: levelText.Text = "第四级"; break;
                case 5: levelText.Text = "第五级"; break;
                default: levelText.Text = "第一级"; break;
            }
            name.Text = cells["Name"].Value.ToString();
            area.Text = cells["Area"].Value.ToString();
            start.Text = cells["Start"].Value.ToString();
            end.Text = cells["End"].Value.ToString();
            riverWidth.Text = cells["RiverWidth"].Value.ToString();
            //ratioTrue.Checked = cells["Ratio"].Value.ToString() == "1";
            //ratioFalse.Checked = cells["Ratio"].Value.ToString() == "1";
            ratio.Text = cells["Ratio"].Value.ToString();
            if (ratio.Text != "0")
            {
                ratioTrue.Checked = true;
            }
            else {
                ratioFalse.Checked = true;
            }
            elevation.Text = cells["Elevation"].Value.ToString();
            line.Text = cells["Line"].Value.ToString();
            allowTrue.Checked = cells["Allow"].Value.ToString() == "1";
            allowFalse.Checked = cells["Allow"].Value.ToString() == "1";
            allowCustom.Checked = cells["Allow"].Value.ToString() == "1";
            safe.Text = cells["Safe"].Value.ToString();
            
            if (level.Value == 1) {
                if (safe.Text == "0.5") { allowTrue.Checked = true; } else if (safe.Text == "1") { allowFalse.Checked = true; } else { allowCustom.Checked = true; }
            } else if (level.Value == 2)
            {
                if (safe.Text == "0.4") { allowTrue.Checked = true; } else if (safe.Text == "0.8") { allowFalse.Checked = true; } else { allowCustom.Checked = true; }
            }
            else if (level.Value == 3)
            {
                if (safe.Text == "0.4") { allowTrue.Checked = true; } else if (safe.Text == "0.7") { allowFalse.Checked = true; } else { allowCustom.Checked = true; }
            }
            else if (level.Value == 4)
            {
                if (safe.Text == "0.3") { allowTrue.Checked = true; } else if (safe.Text == "0.6") { allowFalse.Checked = true; } else { allowCustom.Checked = true; }
            }
            else if (level.Value == 5)
            {
                if (safe.Text == "0.3") { allowTrue.Checked = true; } else if (safe.Text == "0.5") { allowFalse.Checked = true; } else { allowCustom.Checked = true; }
            }

            depth.Text = cells["Depth"].Value.ToString();
            channelWidth.Text = cells["ChannelWidth"].Value.ToString();
            threshold.Text = cells["Threshold"].Value.ToString();
            if (cells["Dredging"].Value.ToString() == "不需要清淤.")
            {
                dredging.ForeColor = System.Drawing.Color.Green;
            }
            else if (cells["Dredging"].Value.ToString() == "需要对该河道进行清淤.")
            {
                dredging.ForeColor = System.Drawing.Color.Red;
            }
            else
            {
                dredging.ForeColor = System.Drawing.Color.Blue;
            }
            dredging.Text = cells["Dredging"].Value.ToString();
        }

        private void dataGridView_CellMouseDown(object sender, DataGridViewCellMouseEventArgs e)
        {
            if (e.Button == MouseButtons.Right)
            {
                dataGridView1.ClearSelection();
                dataGridView1.Rows[e.RowIndex].Selected = true;
                dataGridViewMenu.Show(MousePosition.X, MousePosition.Y);
            }
        }

        private void menuDelete_Click(object sender, EventArgs e)
        {
            var id = Convert.ToInt32(dataGridView1.SelectedRows[0].Cells["Id"].Value);
            var db = new WaterResourcesDb<WaterSecurity>();
            int num;
            if (id > 0)
            {
                num = db.Drop(id);
                if (num == 1)
                {
                    MessageBox.Show("删除成功");
                    var wsSource = db.Find();
                    foreach (WaterSecurity we in wsSource)
                    {
                        if (we.Level == 1) { we.Levelname = "第一级"; }
                        else if (we.Level == 2) { we.Levelname = "第二级"; }
                        else if (we.Level == 3) { we.Levelname = "第三级"; }
                        else if (we.Level == 4) { we.Levelname = "第四级"; }
                        else if (we.Level == 5) { we.Levelname = "第五级"; }
                    }
                    dataGridView1.DataSource = wsSource;
                    dataGridView1.DataSource = wsSource;
                    mapDataGridViewHeader();
                }
                else
                {
                    MessageBox.Show("删除失败");
                }
            }
            else
            {
                MessageBox.Show("此列ID未找到");
            }
        }

        private void importMenu_Click(object sender, EventArgs e)
        {
            openFileDialog.Filter = "Excel文件|*.xlsx;*.xlsm";
            if (openFileDialog.ShowDialog() == DialogResult.OK)
            {
                try
                {
                    using (var xlw = new XLWorkbook(openFileDialog.FileName))
                    {
                        var db = new WaterResourcesDb<WaterSecurity>();
                        var rows = xlw.Worksheet(1).RowsUsed();
                        var firstCellRange = new List<string> { "河道防洪排涝等级", "第一级", "第二级", "第三级", "第四级", "第五级", "1", "2", "3", "4", "5" };
                        int i = 0;
                        foreach (var row in rows)
                        {
                            i = i + 1;
                            var cells = row.CellsUsed().AsList();
                            if (firstCellRange.IndexOf(cells[0].Value.ToString()) < 0 || cells.Count < 17)
                            {
                                MessageBox.Show("文件内容不符合模板，请确认后重新上传。");
                                return;
                            }
                            if (cells[0].Value.ToString() == "河道防洪排涝等级")
                            {
                                // 标题栏，跳过
                                continue;
                            }
                            if (!cells[2].Value.ToString().Contains("市") && !cells[2].Value.ToString().Contains("县") && !cells[2].Value.ToString().Contains("区") && !cells[2].Value.ToString().Contains("乡") && !cells[2].Value.ToString().Contains("一般"))
                            {
                                MessageBox.Show("第" + i + "行数据的河道所属辖区，没有关键字【市】或者【县】或者【区】或者【乡】或者【一般】！请先维护！");
                                return;
                            }
                            if (cells[1].Value.ToString() != "")
                            {
                                var dba = new WaterResourcesDb<WaterSecurity>();
                                string sql = "select * from water_security where Area='" + cells[2].Value.ToString() + "' and Name='" + cells[1].Value.ToString() + "'";
                                var w = dba.FindFirst(sql, new WaterSecurity());
                                if (w != null)
                                {
                                    int level1;
                                    switch (cells[0].Value.ToString())
                                    {
                                        case "第一级": level1 = 1; break;
                                        case "第二级": level1 = 2; break;
                                        case "第三级": level1 = 3; break;
                                        case "第四级": level1 = 4; break;
                                        case "第五级": level1 = 5; break;
                                        default: level1 = 1; break;
                                    }
                                    w.Level = level1;
                                    w.Name = cells[1].Value.ToString();
                                    w.Area = cells[2].Value.ToString();
                                    w.Start = cells[3].Value.ToString();
                                    w.End = cells[4].Value.ToString();
                                    w.RiverWidth = Convert.ToDecimal(cells[5].Value);
                                    w.Ratio = Convert.ToDecimal(cells[7].Value);
                                    w.Elevation = Convert.ToDecimal(cells[8].Value);
                                    w.Line = Convert.ToDecimal(cells[9].Value);
                                    w.Allow = Convert.ToDecimal(cells[10].Value);
                                    w.Safe = Convert.ToDecimal(cells[11].Value);
                                    w.Depth = Convert.ToDecimal(cells[12].Value);
                                    w.ChannelWidth = Convert.ToDecimal(cells[13].Value);
                                    w.Threshold = Convert.ToDecimal(cells[14].Value);
                                    w.Dredging = cells[15].Value.ToString();
                                    if (cells[16].Value.ToString() == "")
                                    {
                                        w.Time = DateTime.Now;
                                    }
                                    else
                                    {
                                        w.Time = Convert.ToDateTime(cells[16].Value.ToString());
                                    }
                                    dba.Edit(w);
                                    continue;
                                }
                            }
                            int level;
                            switch (cells[0].Value.ToString())
                            {
                                case "第一级": level = 1; break;
                                case "第二级": level = 2; break;
                                case "第三级": level = 3; break;
                                case "第四级": level = 4; break;
                                case "第五级": level = 5; break;
                                default: level = 1; break;
                            }
                            var t = DateTime.Now;
                            if (cells[16].Value.ToString() == "")
                            {
                                t = DateTime.Now;
                            }
                            else
                            {
                                t = Convert.ToDateTime(cells[16].Value.ToString());
                            }
                            var model = new WaterSecurity
                            {
                                Level = level,
                                Name = cells[1].Value.ToString(),
                                Area = cells[2].Value.ToString(),
                                Start = cells[3].Value.ToString(),
                                End = cells[4].Value.ToString(),
                                RiverWidth = Convert.ToDecimal(cells[5].Value),
                                Ratio = Convert.ToDecimal(cells[7].Value),
                                Elevation = Convert.ToDecimal(cells[8].Value),
                                Line = Convert.ToDecimal(cells[9].Value),
                                Allow = Convert.ToDecimal(cells[10].Value),
                                Safe = Convert.ToDecimal(cells[11].Value),
                                Depth = Convert.ToDecimal(cells[12].Value),
                                ChannelWidth = Convert.ToDecimal(cells[13].Value),
                                Threshold = Convert.ToDecimal(cells[14].Value),
                                Dredging = cells[15].Value.ToString(),
                                Time = t,
                            };
                            db.Save(model);
                        }
                        MessageBox.Show("导入成功");
                        var wsSource = db.Find();
                        foreach (WaterSecurity we in wsSource)
                        {
                            if (we.Level == 1) { we.Levelname = "第一级"; }
                            else if (we.Level == 2) { we.Levelname = "第二级"; }
                            else if (we.Level == 3) { we.Levelname = "第三级"; }
                            else if (we.Level == 4) { we.Levelname = "第四级"; }
                            else if (we.Level == 5) { we.Levelname = "第五级"; }
                        }
                        dataGridView1.DataSource = wsSource;
                        mapDataGridViewHeader();
                    }
                }
                catch (IOException)
                {
                    MessageBox.Show("文件读取错误，文件进程被占用，请关闭后重试。");
                }
                catch (FileFormatException)
                {
                    MessageBox.Show("文件格式错误，程序只支持Excel 2007及以上版本，请重新保存为xlsx格式后重试。");
                }
                catch (Exception exp)
                {
                    MessageBox.Show("超出预期的错误:" + exp.Message);
                }
            }
        }

        private void exportMenu_Click(object sender, EventArgs e)
        {
            var saveFileDialog = new SaveFileDialog();
            saveFileDialog.Filter = "Excel文件|*.xlsx";
            saveFileDialog.FileName = "水安全数据" + DateTime.Now.ToString("D") + ".xlsx";
            if (saveFileDialog.ShowDialog() == DialogResult.OK)
            {
                try
                {
                    var dt = new DataTable();

                    foreach (DataGridViewColumn column in dataGridView1.Columns)
                    {
                        dt.Columns.Add(column.HeaderText, column.ValueType);
                    }

                    foreach (DataGridViewRow row in dataGridView1.Rows)
                    {
                        dt.Rows.Add();
                        foreach (DataGridViewCell cell in row.Cells)
                        {
                            dt.Rows[dt.Rows.Count - 1][cell.ColumnIndex] = cell.Value.ToString();
                        }
                    }

                    using (var xlw = new XLWorkbook())
                    {
                        xlw.Worksheets.Add(dt, "Sheet1");
                        xlw.SaveAs(saveFileDialog.FileName);
                    }
                }
                catch (IOException)
                {
                    MessageBox.Show("文件写入错误，文件进程被占用，请关闭后重试。");
                }
                catch (Exception exp)
                {
                    MessageBox.Show("超出预期的错误:" + exp.Message);
                }
            }
        }

        private void ratioFalse_CheckedChanged(object sender, EventArgs e)
        {
            var textBoxDepth = sender as RadioButton;
            if (textBoxDepth.Checked == true)
            {
                label10.Hide();
                label19.Hide();
                ratio.Hide();
            }
            else {
                label10.Show();
                label19.Show();
                ratio.Show();
            }
        }

        private void allowTrue_CheckedChanged(object sender, EventArgs e)
        {
            var textBoxDepth = sender as RadioButton;
            if (textBoxDepth.Checked == true&& levelText.Text=="第一级") {
                safe.Text = "0.5";
            }else if (textBoxDepth.Checked == true && (levelText.Text == "第二级"|| levelText.Text == "第三级"))
            {
                safe.Text = "0.4";
            }
            else if(textBoxDepth.Checked == true && (levelText.Text == "第四级"|| levelText.Text == "第五级")) {
                safe.Text = "0.3";
            }
        }

        private void allowFalse_CheckedChanged(object sender, EventArgs e)
        {
            var textBoxDepth = sender as RadioButton;
            if (textBoxDepth.Checked == true && levelText.Text == "第一级")
            {
                safe.Text = "1";
            }
            else if (textBoxDepth.Checked == true && levelText.Text == "第二级")
            {
                safe.Text = "0.8";
            }
            else if (textBoxDepth.Checked == true && levelText.Text == "第三级")
            {
                safe.Text = "0.7";
            }
            else if (textBoxDepth.Checked == true && levelText.Text == "第四级")
            {
                safe.Text = "0.6";
            }
            else if (textBoxDepth.Checked == true && levelText.Text == "第五级")
            {
                safe.Text = "0.5";
            }
        }

        private void allowCustom_CheckedChanged(object sender, EventArgs e)
        {
            var textBoxDepth = sender as RadioButton;
            if (textBoxDepth.Checked == true)
            {
                safe.Text = "";
            }
        }

        private void FormWaterSecurity_SizeChanged(object sender, EventArgs e)
        {
            panel1.Height = Height - 40;
        }

        private void button1_Click(object sender, EventArgs e)
        {
            string sql = "select * from water_security where 1=1";
            if (checkname.Text != "")
            {
                sql += " and name like'%" + checkname.Text + "%'";
            }
            if (checkarea.Text != "")
            {
                sql += " and area like'%" + checkarea.Text + "%'";
            }
            if (checklevel.Text == "第一级")
            {
                sql += " and level=1";
            }
            else if (checklevel.Text == "第二级")
            {
                sql += " and level=2";
            }
            else if (checklevel.Text == "第三级")
            {
                sql += " and level=3";
            }
            else if (checklevel.Text == "第四级")
            {
                sql += " and level=4";
            }
            else if (checklevel.Text == "第五级")
            {
                sql += " and level=5";
            }
            if (checktimeone.Value != null && checktimetwo.Value != null && checktimeone.Value <= checktimetwo.Value)
            {
                sql += " and time between '" + checktimeone.Value.ToString("yyyy-MM-dd") + "' and '" + checktimetwo.Value.ToString("yyyy-MM-dd") + "'";
            }
            var db = new WaterResourcesDb<WaterSecurity>();
            var wsSource = db.Find(sql, new WaterSecurity());
            foreach (WaterSecurity we in wsSource)
            {
                if (we.Level == 1) { we.Levelname = "第一级"; }
                else if (we.Level == 2) { we.Levelname = "第二级"; }
                else if (we.Level == 3) { we.Levelname = "第三级"; }
                else if (we.Level == 4) { we.Levelname = "第四级"; }
                else if (we.Level == 5) { we.Levelname = "第五级"; }
            }
            dataGridView1.DataSource = wsSource;
            mapDataGridViewHeader();
        }
    }
}
